import React from 'react';
import Utils from '../../../src/utils/utils'
import {fetch, post} from '../../../src/my_axios/api'
import {Card, Button, Table, Icon, Modal, message, Row, Col, Tabs, Input, List,Collapse} from 'antd';
import './index.less'
// 引入 ECharts 主模块
import echarts from 'echarts/lib/echarts';
// 引入折线图
import 'echarts/lib/chart/line';
import 'echarts/lib/chart/bar';
import 'echarts/lib/chart/scatter';
// 引入提示框和标题组件
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import 'echarts/lib/chart/pie';
import 'echarts/lib/component/legend';
import ChartSearchBar from './../../pages/chart/chart_mange/components/chartSearchBar/index'
import Paho from 'paho-mqtt';
import './index.less'
import moment from 'moment'
const Panel = Collapse.Panel;
export default class AloneMyChart extends React.Component {
    state = {
        collapseKey:'',
        history:'',
        formList: [
            {
                type: 'DatePicker',
                label: '开始日期',
                field: 'startDate',
                placeholder: '请选择日期',
                initialValue: moment(new Date(new Date().getTime() - 1 * 60 * 60 * 1000), 'YYYY-MM-DD'),
            },
            {
                type: 'DatePicker',
                label: '结束日期',
                field: 'endDate',
                placeholder: '请选择日期',
                initialValue: moment(new Date(), 'YYYY-MM-DD'),
            },
            {
                type: 'SELECT',
                label: '取值模式',
                field: 'valueModel',
                placeholder: '请选择模式',
                initialValue: '',
                list: []
            },
            {
                type: 'InputSelect',
                label: '间隔时间',
                field: 'intervalTime',
                placeholder: '',
                initialValue: '',
            },
            {
                type: 'TimeRange',
                label: '',
                field: 'range',
                placeholder: '',
                initialValue: '小时',
            },
        ],
        time_range_list: [],
        currentSeriesList: [],
        colors: ['#ffae6b', '#3182bd', '#1cfff7', '#FD0DD2'],
        mqttData: [],
        dateList: [],//x轴数据
        currentTimeRangeType: '小时',
        topicList:[]
    };
    myChart=null;
    componentWillMount() {
        if( this.props.onRef!==undefined){
            this.props.onRef(this);
        }
        this.myChartClear();
        this.getByTypeDictionary();
        this.getSeriesGroupById();
    }
    componentWillUnmount() {

    }
    collapseOnChange=(e)=>{
        this.setState({
            collapseKey:e
        });
    };
    /**
     * radioGroup改变回调
     */
    radioGroup=(value)=>{
        this.setState({
            currentTimeRangeType: value
        });
        let date=null;
        if(value==='月'){
            var my_date = new Date(), y = my_date.getFullYear(), m = my_date.getMonth();
            var firstDay = new Date(y, m, 1);//当月第一天
            var lastDay = new Date(y, m + 1, 0);//当月最后一天
            let list=[];
            this.state.formList.map((item)=>{
                if(item.label==='开始日期'){
                    item.initialValue=moment(firstDay,'YYYY-MM-DD');
                }else if(item.label==='结束日期'){
                    item.initialValue=moment(lastDay,'YYYY-MM-DD');
                }
                list.push(item)
            });
            this.setState({
                formList:list
            })
        }else{
            if(value==='小时'){
                date=new Date(new Date().getTime() - 1 * 60 * 60 * 1000);
            }else if(value==='4小时'){
                date=new Date(new Date().getTime() - 4 * 60 * 60 * 1000);
            }else if(value==='8小时'){
                date=new Date(new Date().getTime() - 8 * 60 * 60 * 1000);
            }else if(value==='日'){
                date=new Date(new Date().getTime() - 24 * 60 * 60 * 1000);
            }else if(value==='周'){
                date=new Date(new Date().getTime() - 24 * 7 * 60 * 60 * 1000);
            }
        }
        if(date!==null){
            let list=[];
            this.state.formList.map((item)=>{
                if(item.label==='开始日期'){
                    item.initialValue=moment(date,'YYYY-MM-DD');
                }else if(item.label==='结束日期'){
                    item.initialValue=moment(new Date(),'YYYY-MM-DD');
                }
                list.push(item)
            });
            this.setState({
                formList:list
            })
        }
    };
    getByTypeDictionary() {
        fetch('dictionary/get_by_type', {type: '时间范围'}).then(res => {
            if (res.status === 'success') {
                this.setState({
                    time_range_list: res.data
                })
            } else {
                message.error(res.data.message);
            }

        }).catch(err => {
            console.log(err);
        })
    }

    /**
     * 获取趋势组
     */
    getSeriesGroupById(){
        fetch('series_group/get', {id: this.props.series_group_id}).then(res => {
            if (res.status === 'success') {
                this.setState({
                    history:res.data.history
                });
                this.getSeriesList(res.data.history);
            } else {
                message.error(res.data.message);
            }
        }).catch(err => {
            console.log(err);
        });
    }


    /**
     * 获得趋势（tag）
     * @param page
     */
    getSeriesList=(history)=>{
        let params = {
            size: 999,
            sort: '',
            page: '',
            tag: '',
            seriesType: '',
            chart: '',
            seriesGroup: this.props.series_group_id
        };
        fetch('series/list', params).then(res => {
            if (res.status === 'success') {
                this.setState({
                    currentSeriesList: res.data.content,
                }, () => {
                    //获得tagList  先画图表
                    this.getDynamicCharts(history);
                    if(!history){//如果是实时数据，连接mqtt
                        let list=[];
                        res.data.content.map((item)=>{
                            list.push(item.tag.topic)
                        });
                        this.setState({
                            topicList:list
                        });
                        this.props.subscribeTopic(list);
                    }
                });
            } else {
                message.error(res.data.message);
            }
        }).catch(err => {
            console.log(err);
        });
    }
    /**
     * 动态图表
     */
    getDynamicCharts = (history) => {
        this.myChart = echarts.init(document.getElementById('my_chart'));
        this.myChart.clear();//清空画布
        if(this.state.currentSeriesList.length!==0){
            let legend = {data: []};//说明
            let yAxis = [];//Y轴
            let seriesList = [];//数据
            let i = 0;
            let position=true;//代表Y轴在左
            for (let series of this.state.currentSeriesList) {
                let offset=0;
                if(i>1){
                    offset=70
                }
                let yAxisObject = {
                    type: 'value',
                    name: series.tag.topic,
                    min: series.low,
                    max: series.high,
                    interval: (series.high - series.low) / 5,
                    axisLabel: {
                        formatter: '{value}',
                    },
                    axisLine: {
                        lineStyle: {
                            color: this.state.colors[i]
                        }
                    },
                    offset:offset,
                    position:position?'left':'right'
                };
                let type='';
                if(series.series_type === 'LINE'){
                    type='line'
                }else if(series.series_type === 'BAR'){
                    type='bar'
                }else if(series.series_type === 'SCATTER'){
                    type='scatter'
                }
                let seriesObject = {
                    name: series.tag.topic,
                    type: type,
                    lineStyle: {
                        color: this.state.colors[i]
                    },
                    data:[],
                    yAxisIndex:i//选择哪个Y轴展示数据
                };
                if(history){//如果是静态图表
                    seriesObject.data=[10,20,30,40]
                }else {
                    seriesObject.data=[];
                }
                seriesList.push(seriesObject);
                yAxis.push(yAxisObject);
                let legendObject={
                    name:series.tag.topic,
                    // textStyle: {
                    //     color:this.state.colors[i]
                    // },
                    backgroundColor:this.state.colors[i]
                };
                legend.data.push(legendObject);//标题
                position=!position;
                i++;
            }
            let xAxis={
                type: 'category',
                //boundaryGap: false,
                data: [],
                axisLabel: {
                    interval:0,//强制设置显示所有标签
                    rotate:30
                }
            };
            if(history){//如果是静态图表
                xAxis.data=['15:20:21','15:30:21','15:40:21','15:50:21',]
            }else {
                xAxis.data=[];
            }

            let option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                        crossStyle: {
                            color: '#999'
                        }
                    }
                },
                grid: [
                    {
                        left: 120,
                        right: 120,
                    },
                ],
                color: ['#ffae6b', '#3182bd', '#1cfff7', '#FD0DD2'],
                legend: legend,
                xAxis: xAxis,
                yAxis: yAxis,
                series: seriesList,
            };
            this.myChart.setOption(option);
        }
    };

    myChartClear=()=>{
        if(this.myChart!==null){
            this.myChart.clear();
        }
    }
    /**
     * 接受消息
     * @param message
     */
    onMessageArrived = (message) => {
        let object = {...message};
        let topic = object.destinationName;
        if (object.payloadString && object.payloadString !== ''&&eval("(" + object.payloadString + ")").v!==undefined) {
            let messageObject = eval("(" + object.payloadString + ")");
            if(this.state.topicList.indexOf(topic)!==-1){
                if(!isNaN(messageObject.v)){//需要数值类型
                    this.updateChart(messageObject,topic);
                }else{
                    console.log("趋势图：无效的数据")
                }
            }
        }else{
            console.log("数据格式不对，当前数据：" + object.payloadString)
        }
    };
    /**
     * 更新图表
     */
    updateChart=(messageObject,topic)=>{
        let myChart = echarts.init(document.getElementById('my_chart'));
        /**
         * 保存每次点击的时间数据
         * @type {Date}
         */
        var now = new Date();
        var nowTime = now.toLocaleString();
        var time = nowTime.substring(11, 20); //截取时间
        let dateList = this.state.dateList;
        dateList.push(time);
        this.setState({
            dateList
        });
        let seriesList = [];//数据
        let myXAxis = {
            type: 'category',
            // boundaryGap: false,
            data:this.state.dateList
        };
        let i = 0;
        /**
         * 保存接收的数据
         * @type {Array}
         */
        let mqttData = this.state.mqttData;
        for (let series of this.state.currentSeriesList){
            if(topic===series.tag.topic){
                //添加数值
                let dataObject = {
                    topic: series.tag.topic,
                    value: messageObject.v,
                };
                mqttData.push(dataObject);
            }else{
                let dataObject = {
                    topic: series.tag.topic,
                    value: '',
                };
                mqttData.push(dataObject);
            }
            let type='';
            if(series.series_type === 'LINE'){
                type='line'
            }else if(series.series_type === 'BAR'){
                type='bar'
            }else if(series.series_type === 'SCATTER'){
                type='scatter'
            }
            let seriesObject = {
                name: series.tag.topic,
                type: type,
                lineStyle: {
                    color: this.state.colors[i]
                },
                data:[],
                yAxisIndex:i//选择哪个Y轴展示数据
            };
            seriesList.push(seriesObject);
            i++;
        }
        this.setState({
            mqttData
        });
        for(let ser of seriesList ){
            let dataList=[];//每个series的dataList
            for (let data of this.state.mqttData) {//循环获得的所有数据
                if (data.topic===ser.name) {
                    dataList.push(data.value)
                }
            }
            ser.data=dataList;
        }
        myChart.setOption({
            xAxis:myXAxis,
            series:seriesList,
        });
    };
    /**
     * 向前或者向后
     */
    forAndBack = (boolean) => {
        let dateList = [];
        if (this.state.currentTimeRangeType === '月') {
            dateList = this.addAndSubtract('月', boolean);
        } else if (this.state.currentTimeRangeType === '小时') {
            dateList = this.addAndSubtract('小时', boolean);
        } else if (this.state.currentTimeRangeType === '4小时') {
            dateList = this.addAndSubtract('4小时', boolean);
        } else if (this.state.currentTimeRangeType === '8小时') {
            dateList = this.addAndSubtract('8小时', boolean);
        } else if (this.state.currentTimeRangeType === '日') {
            dateList = this.addAndSubtract('日', boolean);
        } else if (this.state.currentTimeRangeType === '周') {
            dateList = this.addAndSubtract('周', boolean);
        }
        let list = [];
        this.state.formList.map((item) => {
            if (item.label === '开始日期') {
                item.initialValue = dateList[0];
            } else if (item.label === '结束日期') {
                item.initialValue = dateList[1];
            }
            list.push(item)
        });
        this.setState({
            formList: list
        })

    };
    addAndSubtract = (value, boolean) => {
        let list = [];
        let startDate = this.state.formList[0].initialValue;
        let endDate = this.state.formList[1].initialValue;
        // console.log(startDate.format('YYYY-MM-DD HH:mm:ss'));
        if (boolean) {
            if (value === '小时') {
                startDate.subtract(1, 'h');
                endDate.subtract(1, 'h')
            } else if (value === '4小时') {
                startDate.subtract(4, 'h');
                endDate.subtract(4, 'h')
            } else if (value === '8小时') {
                startDate.subtract(8, 'h');
                endDate.subtract(8, 'h')
            } else if (value === '日') {
                startDate.subtract(1, 'd');
                endDate.subtract(1, 'd')
            } else if (value === '周') {
                startDate.subtract(1, 'w');
                endDate.subtract(1, 'w')
            } else if (value === '月') {
                let startDateType=(new Date(startDate.valueOf()));
                let firstDay = new Date(startDateType.getFullYear(), startDateType.getMonth(), 1);//当月第一天
                let lastDay = new Date(startDateType.getFullYear(), startDateType.getMonth()+1, 0);//当月第一天
                startDate = moment(firstDay, 'YYYY-MM-DD');
                endDate = moment(lastDay, 'YYYY-MM-DD');
                startDate.subtract(1, 'M');
                endDate.subtract(1, 'M')
            }
        } else {
            if (value === '小时') {
                startDate.add(1, 'h');
                endDate.add(1, 'h')
            } else if (value === '4小时') {
                startDate.add(4, 'h');
                endDate.add(4, 'h')
            } else if (value === '8小时') {
                startDate.add(8, 'h');
                endDate.add(8, 'h')
            } else if (value === '日') {
                startDate.add(1, 'd');
                endDate.add(1, 'd')
            } else if (value === '周') {
                startDate.add(1, 'w');
                endDate.add(1, 'w')
            } else if (value === '月') {
                let startDateType=(new Date(startDate.valueOf()));
                let endDateType=(new Date(endDate.valueOf()));
                let firstDay = new Date(startDateType.getFullYear(), startDateType.getMonth(), 1);//当月第一天
                let lastDay = new Date(endDateType.getFullYear(), endDateType.getMonth()+1, 0);//当月第一天
                startDate = moment(firstDay, 'YYYY-MM-DD');
                endDate = moment(lastDay, 'YYYY-MM-DD');
                startDate.add(1, 'M');
                endDate.add(1, 'M')
            }
        }
        list.push(startDate);
        list.push(endDate);
        return list;
    };

    /**
     * 查询
     * @param fieldsValue
     */
    filterSubmit=(fieldsValue)=>{
        console.log(fieldsValue);
    };

    render() {
        return (
            <div className="my_chart_overflow" style={{height:(window.innerHeight-150),paddingRight:10}}>
                {
                    this.state.history?  <Collapse activeKey={this.state.collapseKey} onChange={this.collapseOnChange}>
                        <Panel key="1">
                            <ChartSearchBar
                                wrappedComponentRef={(inst) => this.ChartSearchBar = inst}
                                radioGroup={this.radioGroup}
                                forAndBack={this.forAndBack}
                                filterSubmit={this.filterSubmit}
                                timeRangeList={this.state.time_range_list}
                                formList={this.state.formList}>
                            </ChartSearchBar>
                        </Panel>
                    </Collapse>:null
                }
                <div id="my_chart" className="chart_div" style={{width: '100%',height:(window.innerHeight-200),marginTop:20}}>
                </div>
            </div>
        )
    }
}